/*********************************************************************************
 *      Copyright:  (C) 2022 Zhang xiangyun<1327295677@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  socket.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(20/04/22)
 *         Author:  Zhang xiangyun <1327295677@qq.com>
 *      ChangeLog:  1, Release initial version on "20/04/22 14:37:36"
 *                 
 ********************************************************************************/
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <linux/types.h>
#include <asm/byteorder.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <getopt.h>
#include "logger.h"
#include "pack.h"

int client_socket_connect(char *server_ip,int server_port,int *socket_fd);
//int client_socket_senddata(int socket_fd,float temp);
int socketconnected(int socket_fd);
int socket_senddata(int socket_fd,char *pack_buf,int size);
/* socket init */
int client_socket_connect(char *server_ip,int server_port,int *socket_fd)
{
	struct sockaddr_in    serv_addr;
	int                   rv=-1;

#if 1
	if((*socket_fd=socket(AF_INET,SOCK_STREAM,0))<0)
	{
		log_error("create socket failure:%s\n",strerror(errno));
		return -1;
	}
    //printf("socket_fd:%d,ip:%s,port:%d\n",socket_fd,server_ip,server_port);
	memset(&serv_addr,0,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(server_port);
	inet_aton(server_ip,&serv_addr.sin_addr);

	rv=(connect(*socket_fd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)));
#endif 
	return rv;
}


int socket_senddata(int socket_fd,char *pack_buf,int size)
{
	int     rv_write=-1;

	//printf("write_buf:%s\n",write_buf);
	rv_write=write(socket_fd,pack_buf,size);
	if(rv_write<0)
	{
		log_error("send data failure!\n ");
		return -1;
	}
	log_info("write data to server\n");
	return rv_write;
}

int socketconnected(int socket_fd)
{
	struct tcp_info    info;
	int                len;
	len=sizeof(info);

	if(socket_fd<=0)
	{
		log_error("the socket is not conneted!\n");
		return 0;
	}

	if(getsockopt(socket_fd,IPPROTO_TCP,TCP_INFO,&info,(socklen_t*)&len)<0)
	{
		log_error("getsockopt() TCP_INFO error\n");
	}

	if(info.tcpi_state ==1)/* TCP_ESTABLISHED =1 */
	{
		log_warn("socket connected!\n");
		return 1;
	}
	else
	{
		log_warn("socket disconnected!\n");
		return 0;
	}
}


 
